package heap;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;


/*
 *@description 前k个高频元素
 *@author hkfan
 *@version 1.0
 *@create 2025/5/16 14:13
 */
public class LeetCode_347 {

    class Node{
        Integer num;
        Integer count;

        public Node(Integer num, Integer count) {
            this.num = num;
            this.count = count;
        }
    }

    public int[] topKFrequent(int[] nums, int k) {
        //1. 定义map存储数据
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }

        //2. 使用优先级队列输出结果,定义大根堆
        PriorityQueue<Node> minHeap = new PriorityQueue<>((a,b)->{
            return b.count-a.count;
        });
        for (Integer num : map.keySet()) {
            minHeap.add(new Node(num,map.get(num)));
        }

        //3. 存储结果
        int[] res = new int[k];
        for (int i = k-1; i >= 0; i--) {
            res[i]=minHeap.remove().num;
        }
        return res;
    }


}
